//
//  UIButton+layout.m
//  MIApp
//
//  Created by ZE KANG on 16/9/21.
//  Copyright © 2016年 HongJi. All rights reserved.
//

#import "UIButton+layout.h"
#import <objc/runtime.h>
#import "UIView+Base.h"
static char topNameKey;
static char rightNameKey;
static char bottomNameKey;
static char leftNameKey;

@implementation UIButton (layout)

- (void)layoutButtonWithEdgeInsetsStyle:(MKButtonEdgeInsetsStyle)style
                        imageTitleSpace:(CGFloat)spacing
{
    
//    CGSize size = self.bounds.size;
//    CGSize imageSize = self.imageView.image.size;
//    CGSize titleSize = self.titleLabel.bounds.size;
//
//    UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
//    UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;
//    switch (style) {
//        case MKButtonEdgeInsetsStyleLeft:
//        {
//           [self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
//            imageEdgeInsets = UIEdgeInsetsMake(0,0,0,spacing);
//            labelEdgeInsets = UIEdgeInsetsMake(0,spacing, 0,0);
//        }
//            break;
//            
//        case MKButtonEdgeInsetsStyleRight:
//        {
//            [self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
//            imageEdgeInsets = UIEdgeInsetsMake(0, size.width/2 - imageSize.width/2 + titleSize.width/2+spacing, 0, 0);
//            labelEdgeInsets = UIEdgeInsetsMake(0, size.width/2 - 3 *imageSize.width/2 - titleSize.width/2-spacing, 0, 0);
//        }
//            break;
//            
//        case MKButtonEdgeInsetsStyleTop:
//        {
//            
//            [self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
//            imageEdgeInsets = UIEdgeInsetsMake(-imageSize.height-spacing,size.width/2 - imageSize.width/2, 0, 0);
//            labelEdgeInsets = UIEdgeInsetsMake(0,size.width/2 -titleSize.width/2 -imageSize.width,-titleSize.height-spacing,0);
//        }
//            break;
//            
//        case MKButtonEdgeInsetsStyleBottom:
//        {
//            [self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
//            imageEdgeInsets = UIEdgeInsetsMake(imageSize.height+spacing,size.width/2 - imageSize.width/2, 0, 0);
//            labelEdgeInsets = UIEdgeInsetsMake(-titleSize.height-spacing, size.width/2 - titleSize.width/2 -imageSize.width, 0, 0);
//        }
//            break;
//    }
//        // 4. 赋值
//        self.titleEdgeInsets = labelEdgeInsets;
//        self.imageEdgeInsets = imageEdgeInsets;
//    
//}



    
    
    CGSize size = self.frame.size;
    CGSize imageSize = self.imageView.image.size;
    CGSize titleSize = self.titleLabel.frame.size;
    
    UIEdgeInsets imageEdgeInsets = UIEdgeInsetsZero;
    UIEdgeInsets labelEdgeInsets = UIEdgeInsetsZero;
    switch (style) {
        case MKButtonEdgeInsetsStyleRight:
        {
            titleSize = [self.titleLabel sizeThatFits:CGSizeMake(MAXFLOAT,size.height)];
            imageEdgeInsets = UIEdgeInsetsMake(0, titleSize.width + spacing, 0, -titleSize.width);
            labelEdgeInsets = UIEdgeInsetsMake(0, -imageSize.width - spacing, 0, imageSize.width);
        }
            break;
            
        case MKButtonEdgeInsetsStyleLeft:
        {
            imageEdgeInsets = UIEdgeInsetsMake(0, -spacing, 0, spacing);
            labelEdgeInsets = UIEdgeInsetsMake(0, spacing, 0, -spacing);
        }
            break;
            
        case MKButtonEdgeInsetsStyleTop:
        {
            //    CGSize textSize = [self.titleLabel.text sizeWithFont:self.titleLabel.font];
            CGSize textSize = [self.titleLabel sizeThatFits:CGSizeMake(0, 0)];
            CGSize frameSize = CGSizeMake(ceilf(textSize.width), ceilf(textSize.height));
            if (titleSize.width + 0.5 < frameSize.width) {
                titleSize.width = frameSize.width;
            }
            CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);
            imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height) - spacing, 0, 0, - titleSize.width +2.f);
            labelEdgeInsets = UIEdgeInsetsMake(0, - imageSize.width, - (totalHeight - titleSize.height) + spacing, 0);
        }
            break;
            
        case MKButtonEdgeInsetsStyleBottom:
        {
            imageEdgeInsets = UIEdgeInsetsMake(0, 0, -titleSize.height-spacing/2.0, -titleSize.width);
            labelEdgeInsets = UIEdgeInsetsMake(-titleSize.height-spacing/2.0, -titleSize.width, 0, 0);
        }
            break;
    }
    // 4. 赋值
    self.titleEdgeInsets = labelEdgeInsets;
    self.imageEdgeInsets = imageEdgeInsets;
 
}

- (void)setBackgroundImage:(UIImage*)image
{
    CGRect rect;
    rect = self.frame;
    rect.size = image.size; // set button size as image size
    self.frame = rect;
    
    [self setBackgroundImage:image forState:UIControlStateNormal];
}

- (void)setBackgroundImageByName:(NSString*)imageName
{
    [self setBackgroundImage:[UIImage imageNamed:imageName]];
}










- (void)setProperty:(UIColor *)backgroundColor textColor:(UIColor *)textColor font:(CGFloat)font title:(NSString *)title{
    if (backgroundColor != nil) {
        self.backgroundColor = backgroundColor;
    }
    
    if (title != nil) {
        [self setTitle:title forState:UIControlStateNormal];
    }
    
    if (textColor != nil) {
        [self setTitleColor:textColor forState:UIControlStateNormal];
    }
    
    if (font > 0) {
        self.titleLabel.font = [UIFont systemFontOfSize:font];
    }
    
    
    
}



@end



@implementation UIButton (OF)
-(void)setNormalsetAttTitle:(NSAttributedString *)title{
    if (title) {
        [self setAttributedTitle:title forState:UIControlStateNormal];
    }
}
-(void)setNormalTitle:(NSString *)title{
    if (title) {
        [self setTitle:title forState:UIControlStateNormal];
    }
}
-(void)setSelectTitle:(NSString *)title{
    if (title) {
        [self setTitle:title forState:UIControlStateSelected];
    }
}
-(void)setNormalTitleColor:(UIColor *)titleColor{
    if (titleColor) {
        [self setTitleColor:titleColor forState:UIControlStateNormal];
    }
}
-(void)setSelectTitleColor:(UIColor *)titleColor{
    if (titleColor) {
        [self setTitleColor:titleColor forState:UIControlStateSelected];
    }
    
}

-(void)setTitleFont:(float)font{
    if (font) {
        self.titleLabel.font = kSysFont(font);
    }
}

-(void)setTitleTextAlignment:(UIControlContentHorizontalAlignment)textAlignment
{
    self.contentHorizontalAlignment = textAlignment;
}


-(void)setNormalImage:(UIImage *)image{
    [self setImage:image forState:UIControlStateNormal];
}
-(void)setSelectImage:(UIImage *)selectimage{
    [self setImage:selectimage forState:UIControlStateSelected];
}

-(void)setNormalBackImage:(UIImage *)backImage{
    [self setBackgroundImage:backImage forState:UIControlStateNormal];
}
-(void)setSelectBackImage:(UIImage *)selectBackImage{
    [self setBackgroundImage:selectBackImage forState:UIControlStateSelected];
}
-(void)AddTarget:(id)target Action:(SEL)action{
    if (target!=nil &&action != nil) {
        [self addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    }
}

- (void)setNormalColor:(NSString *)normalColor
{
    // 使用颜色创建UIImage
    CGSize imageSize = self.bounds.size;
    UIGraphicsBeginImageContextWithOptions(imageSize, 0, [UIScreen mainScreen].scale);
    
    UIColor *color = [UIColor colorWithHexString:normalColor];
    [color set];
    UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));
    UIImage *pressedColorImg = UIGraphicsGetImageFromCurrentImageContext();
    
    
    [self setBackgroundImage:pressedColorImg forState:UIControlStateNormal];
    
    color = [color colorWithAlphaComponent:0.5];
    [color set];
    UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));
    pressedColorImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    [self setBackgroundImage:pressedColorImg forState:UIControlStateHighlighted];
    
    self.layer.cornerRadius = 2.0f;
    self.layer.masksToBounds = YES;
    self.opaque = NO;
}

-(void)setImageWhenHighlighted:(BOOL)Highlighted
{
    self.adjustsImageWhenHighlighted = Highlighted;
    //或者在创建的时候
    //UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
}

- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state
{
    [self setBackgroundImage:[UIButton imageWithColor:backgroundColor] forState:state];
}

+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}


- (void)setNormalBgColor:(UIColor *)normalColor selectedBgColor:(UIColor *)selectedColor highLightedBgColor:(UIColor *)highLightedColor size:(CGSize)size
{
    CGSize imageSize = size;
    UIGraphicsBeginImageContextWithOptions(imageSize, 0, [UIScreen mainScreen].scale);
    
    UIColor *color ;
    UIImage *img;
    if (normalColor) {
        color = normalColor;
        [color set];
        UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));
        img = UIGraphicsGetImageFromCurrentImageContext();
        [self setBackgroundImage:img forState:UIControlStateNormal];
    }
    
    if (selectedColor) {
        color = selectedColor;
        [color set];
        UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));
        img = UIGraphicsGetImageFromCurrentImageContext();
        [self setBackgroundImage:img forState:UIControlStateSelected];
    }
    
    if (highLightedColor) {
        color = highLightedColor;
        [color set];
        UIRectFill(CGRectMake(0, 0, imageSize.width, imageSize.height));
        img = UIGraphicsGetImageFromCurrentImageContext();
        [self setBackgroundImage:img forState:UIControlStateHighlighted];
    }
    
    UIGraphicsEndImageContext();
    
    self.layer.masksToBounds = YES;
    self.opaque = NO;
}

- (void)setNormalBgColor:(UIColor *)normalColor selectedBgColor:(UIColor *)selectedColor highLightedBgColor:(UIColor *)highLightedColor
{
    [self setNormalBgColor:normalColor selectedBgColor:selectedColor highLightedBgColor:highLightedColor size:self.bounds.size];
}

- (void)setNormalBgColor:(UIColor *)normalColor selectedBgColor:(UIColor *)selectedColor size:(CGSize)size
{
    [self setNormalBgColor:normalColor selectedBgColor:selectedColor highLightedBgColor:nil size:size];
}

- (void)setNormalBgColor:(UIColor *)normalColor selectedBgColor:(UIColor *)selectedColor
{
    [self setNormalBgColor:normalColor selectedBgColor:selectedColor size:self.bounds.size];
}

- (void)setNormalBg:(NSString *)normalHex selectedBg:(NSString *)selectedHex size:(CGSize)size
{
    [self setNormalBgColor:[UIColor colorWithHexString:normalHex] selectedBgColor:[UIColor colorWithHexString:selectedHex] size:size];
}


- (void)setNormalBg:(NSString *)normalHex selectedBg:(NSString *)selectedHex
{
    [self setNormalBg:normalHex selectedBg:selectedHex size:self.bounds.size];
}


@end


@implementation UIButton (Init)

+(instancetype)initWithTitle:(NSString *)title titleColor:(NSString *)color titleFont:(CGFloat)font
{
    UIButton *button = ({
        UIButton * b = [self buttonWithType:UIButtonTypeCustom];
        if (title) {
            [b setNormalTitle:title];
        }
        if (color) {
            [b setNormalTitleColor:hexCOLOR(color)];
        }
        if (font!=0) {
            b.titleLabel.font = kSysFont(kFitW(font));
        }
        b;
    });
    
    return button;
}


+(instancetype)initWithImageName:(NSString *)imageName
{
    UIButton *button = ({
        UIButton * b = [self buttonWithType:UIButtonTypeCustom];
        if (imageName) {
            [b setNormalImage:[UIImage imageNamed:imageName]];
        }
        b;
    });
    
    return button;
}

-(void)setBorder
{
    self.borderColor = [UIColor colorWithHexString:@"0xb6b6b6"];
    self.borderWidth = 1/[UIScreen mainScreen].scale;
}
@end


@implementation UIButton (EnlargeTouchArea)


- (void) setEnlargeEdgeWithTop:(CGFloat) top right:(CGFloat) right bottom:(CGFloat) bottom left:(CGFloat) left
{
    objc_setAssociatedObject(self, &topNameKey, [NSNumber numberWithFloat:top], OBJC_ASSOCIATION_COPY_NONATOMIC);
    objc_setAssociatedObject(self, &rightNameKey, [NSNumber numberWithFloat:right], OBJC_ASSOCIATION_COPY_NONATOMIC);
    objc_setAssociatedObject(self, &bottomNameKey, [NSNumber numberWithFloat:bottom], OBJC_ASSOCIATION_COPY_NONATOMIC);
    objc_setAssociatedObject(self, &leftNameKey, [NSNumber numberWithFloat:left], OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (CGRect) enlargedRect
{
    NSNumber* topEdge = objc_getAssociatedObject(self, &topNameKey);
    NSNumber* rightEdge = objc_getAssociatedObject(self, &rightNameKey);
    NSNumber* bottomEdge = objc_getAssociatedObject(self, &bottomNameKey);
    NSNumber* leftEdge = objc_getAssociatedObject(self, &leftNameKey);
    if (topEdge && rightEdge && bottomEdge && leftEdge)
    {
        return CGRectMake(self.bounds.origin.x - leftEdge.floatValue,
                          self.bounds.origin.y - topEdge.floatValue,
                          self.bounds.size.width + leftEdge.floatValue + rightEdge.floatValue,
                          self.bounds.size.height + topEdge.floatValue + bottomEdge.floatValue);
    }
    else
    {
        return self.bounds;
    }
}

- (UIView*) hitTest:(CGPoint) point withEvent:(UIEvent*) event
{
    CGRect rect = [self enlargedRect];
    if (CGRectEqualToRect(rect, self.bounds))
    {
        return [super hitTest:point withEvent:event];
    }
    return CGRectContainsPoint(rect, point) ? self : nil;
}


@end


@implementation UIButton (Block)

- (void)onPerformTo:(void(^)(id sender))Toblock Do:(void(^)(id sender))Doblock
{
    if (!Toblock||!Doblock) {
        return;
    }
    
    [self setEnabled:NO];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 并行执行的线程一
        if (Toblock) {
            Toblock(self);
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            // 汇总结果
            if (Toblock&&Doblock) {
                [self setEnabled:YES];
                Doblock(self);
            }
        });
    });
}

@end
@implementation UIButton (Timer)

-(void)onStartTimerForTitle:(NSString *)title Block:(dispatch_block_t)block{
    __block int timeout = 59.f;
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        
        int sectonds = timeout%60;
        NSString *strTimer = [NSString stringWithFormat:@"%.2d",sectonds];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self setTitle:[NSString stringWithFormat:@"%@后重发",strTimer] forState:UIControlStateNormal];
            self.userInteractionEnabled = NO;
            if (timeout<=0){
                dispatch_source_cancel(timer);
                if (block) {
                    block();
                }
                [self setTitle:title forState:UIControlStateNormal];
                self.userInteractionEnabled = YES ;
            }
        });
        
        timeout--;
        
    });
    dispatch_resume(timer);
}

@end

